package ThreadProjectTest.sync;

/*
 * Author: JacksonCoder
 * FileName: BankAccount
 * Version: 1.0.0
 */
public class BankAccount {
    private double balance;

    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }

    // 获取账户余额
    public double getBalance() {
        return balance;
    }

    // 存款方式
    public synchronized void deposit(double amount) {
        if (amount > 0) {
            balance += amount; // add amount
        }
    }

    @Override
    public String toString() {
        return "BankAccount{" + "balance=" + balance + "}";
    }

    // 转账方法， 使用synchronized 确保线程安全
    public synchronized void transfer(BankAccount target, double amount) {
        if (amount > 0 && balance >= amount) {
            balance -= amount;  //
            target.deposit(amount);
            System.out.println("Transferred " + amount + " from " + this + " to " + target);
        } else {
            System.out.println("transfer failed: insufficient funds or invalid amount");
        }
    }

}
